package graphics;

import java.nio.ByteBuffer;

import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;

import org.eclipse.swt.graphics.ImageData;

import com.sun.opengl.util.BufferUtil;

public class TexturesLoader {

	final static int imageColor = 4;

	public static int loadTexture(GL gl, String fname) throws Exception, Exception{

		//		String suffix = fname.split("\\.")[(fname.split("\\.").length -1)];
		//		TextureData textureData = TextureIO.newTextureData(new File(fname),true,suffix);


		ImageData image = new ImageData(fname);
		ByteBuffer buffer = BufferUtil.newByteBuffer(image.width * image.height * imageColor);

		for (int y =0; y < image.height; y++){
			for (int x =0; x < image.width; x++){
				int color = image.getPixel(x, y);
				byte r = (byte)(color & 255);
				byte g = (byte)((color >> 8) & 255);
				byte b = (byte)((color >> 16) & 255);
				byte a = (byte)image.getAlpha(x, y);
				buffer.put(r);
				buffer.put(g);
				buffer.put(b);
				buffer.put(a);
			}	
		}
		buffer.rewind();



		int textureindex[] = new int[1];

		gl.glGenTextures(1, textureindex, 0);
		gl.glBindTexture(GL.GL_TEXTURE_2D, textureindex[0]);
		gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
		gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
		GLU glu = new GLU();
		//		textureData.getBuffer().rewind();
		//		glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, GL.GL_RGB, textureData.getWidth(), textureData.getHeight(), 
		//				GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, textureData.getBuffer());

		glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, GL.GL_RGB, image.width, image.height, 
				GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);

		return textureindex[0];
	}
}



